<template>
  <div>
    <el-form label-position="top">
      <el-form-item label="一、研究目标、主要研究内容" />
      <el-form-item
        v-for="(item, key) in editors"
        :key="key"
        :label="item.title"
      >
        <div v-if="item.subTitle" class="sub-title">{{ item.subTitle }}</div>
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="item.editorRef"
            :default-config="toolbarConfig"
          />
          <Editor
            v-model="item.valueHtml"
            style="height: 400px; overflow-y: hidden"
            :default-config="editorConfig"
            @on-created="handleCreated($event, key)"
          />
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

  const $baseMessage = inject('$baseMessage')

  const editors = reactive({
    necessity: {
      title: '1．必要性',
      editorRef: null,
      valueHtml: '',
    },
    overallResearchGoal: {
      title: '2．研究目标',
      editorRef: null,
      valueHtml: '',
    },
    mainResearchContent: {
      title: '3．主要研究内容',
      editorRef: null,
      valueHtml: '',
    },
    riskIdentification: {
      title: '4．QHSE管理（含节能）',
      subTitle: '（1）风险识别',
      editorRef: null,
      valueHtml: '',
    },
    riskControlMeasures: {
      title: '（2）风险控制与消减措施',
      editorRef: null,
      valueHtml: '',
    },
  })

  const toolbarConfig = {}
  const editorConfig = { placeholder: '请输入内容...' }

  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    for (const key in editors) {
      const editor = editors[key].editorRef
      if (editor == null) return
      editor.destroy()
    }
  })

  const handleCreated = (editor, key) => {
    editors[key].editorRef = editor // 记录 editor 实例，重要！
  }

  const getFormData = () => {
    const params = {}
    for (const key in editors) {
      if (!editors[key].valueHtml) {
        $baseMessage('请填写完整的研究目标、主要研究内容', 'error')
        return false
      }
      params[key] = editors[key].valueHtml
    }
    return params
  }

  const setFormData = ({ projectPlanTaskInfo }) => {
    for (const key in editors) {
      editors[key].valueHtml = projectPlanTaskInfo[key]
    }
  }

  defineExpose({ getFormData, setFormData })
</script>

<style lang="scss" scoped></style>
